#include "music.h"
#include "ui_music.h"
#include <QMouseEvent>
#include <QDebug>
#include <QGraphicsDropShadowEffect>
#include <QVector>
#include <QJsonArray>
#include <QJsonObject>
#include <QUrl>

Music::Music(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Music)
{
    ui->setupUi(this);
    this->initUI();     //初始化界面
    this->initSqlite(); // 初始化数据库
    this->initPlayer();// 初始化播放器
    this->initMusicList();  //初始化音乐列表
    this->connectSignalAndSlot();
}

Music::~Music()
{
    delete ui;
}

//初始化界面
void Music::initUI()
{
    //设置⽆边框窗⼝，即窗⼝将来⽆标题栏
    this->setWindowFlag(Qt::WindowType::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowIcon(QIcon(":/images/tubiao.png"));    //任务栏图标
    ui->max->setEnabled(false);

    // 设置窗⼝背景透明
    this->setAttribute(Qt::WA_TranslucentBackground);

    // 给窗⼝设置阴影效果
    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0,0);       // 设置阴影偏移
    shadowEffect->setColor("#000000");  //设置背景颜色
    // 此处需要将圆⻆半径不能太⼤，否则动画效果有问题，可以设置为10
    shadowEffect->setBlurRadius(10);    // 设置阴影的模糊半径
    this->setGraphicsEffect(shadowEffect);

    // 添加托盘
    // 创建托盘图标
    QSystemTrayIcon* SysTrayIcon = new QSystemTrayIcon(this);
    SysTrayIcon->setIcon(QIcon(":/images/tubiao.png"));

    // 创建托盘菜单
    QMenu* TrayMenu = new QMenu(this);
    TrayMenu->addAction("还原",this,&QWidget::showNormal);
    TrayMenu->addSeparator();
    TrayMenu->addAction("退出",this,&Music::quitMusic);

    // 将托盘菜单添加到托盘图标
    SysTrayIcon->setContextMenu(TrayMenu);

    //显示托盘
    SysTrayIcon->show();

    // 设置BodyLeft中6个btForm的信息
    ui->rec->seticon(":/images/rec.png","推荐",1);
    ui->music->seticon(":/images/music.png","音乐馆",2);
    ui->audio->seticon(":/images/radio.png","电台",3);
    ui->like->seticon(":/images/like.png","我喜欢",4);
    ui->local->seticon(":/images/local.png","本地音乐",5);
    ui->recent->seticon(":/images/recent.png","最近播放",6);

    // 本地下载BtForm动画默认显⽰
    ui->local->showAnimal(true);
    ui->stackedWidget->setCurrentIndex(4);
    currentPage = ui->localpage;

    // 初始化推荐页面
    srand(time(NULL));
    ui->recmusicbox->initRecBoxUi(RandomPicture(),1);
    ui->supplymusicbox->initRecBoxUi(RandomPicture(),2);

    // 按钮的背景图⽚样式去除掉之后，需要设置默认图标
    // 播放控制区按钮图标设定
    ui->play->setIcon(QIcon(":/images/play_2.png"));            // 默认为暂停图标
    ui->playmode->setIcon(QIcon(":/images/shuffle_2.png"));     // 默认为随机播放

    // 创建⾳量调节窗⼝对象并挂到对象树
    volumeTool = new VolumeTool(this);

    // 设置我喜欢、本地⾳乐、最近播放⻚⾯
    ui->likepage->setCommonPageUi("我喜欢",":/images/ilikebg.png");
    ui->localpage->setCommonPageUi("本地⾳乐", ":/images/localbg.png");
    ui->recentpage->setCommonPageUi("最近播放", ":/images/recentbg.png");

    // 实例化LrcWord对象
    lrcPage = new LrcPage(this);
    lrcPage->hide();

    //lrcPage添加动画效果
    lrcAnimation = new QPropertyAnimation(lrcPage,"geometry",this);
    lrcAnimation->setDuration(500);
    lrcAnimation->setStartValue(QRect(10,10+lrcPage->height(),lrcPage->width(),lrcPage->height()));
    lrcAnimation->setEndValue(QRect(10,10,lrcPage->width(),lrcPage->height()));
}

void Music::initPlayer()
{
    // 创建播放器
    player = new QMediaPlayer(this);
    // 创建播放列表
    playList = new QMediaPlaylist(this);
    // 设置播放模式：默认为循环播放
    playList->setPlaybackMode(QMediaPlaylist::Random);
    // 将播放列表设置给播放器
    player->setPlaylist(playList);
    // 默认⾳量⼤⼩设置为20
    player->setVolume(20);

    // QMediaPlayer信号和槽函数关联
    // 播放状态改变时：暂停和播放之间切换
    connect(player,&QMediaPlayer::stateChanged,this,&Music::onPlayStateChanged);
    //关联歌曲时间    媒体持续时⻓更新，即：⾳乐切换，时⻓更新，界⾯上时间也要更新
    connect(player,&QMediaPlayer::durationChanged,this,&Music::onDurationChanged);
    // 播放位置发⽣改变，即已经播放时间更新
    connect(player,&QMediaPlayer::positionChanged,this,&Music::onPositionChanged);
    //关联歌曲信息metaDataAvailableChanged
    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&Music::onMetaDataAvailableChangedChanged);
    //关联播放模式
    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&Music::onPlaybackModeChanged);
    //关联同步
    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&Music::onCurrentIndexChanged);
}

//切换窗口
void Music::connectSignalAndSlot()
{
    // ⾃定义的btFrom按钮点击信号，当btForm点击后，设置对应的堆叠窗⼝
    connect(ui->rec,&BtForm::click,this,&Music::onBtFormClick);
    connect(ui->music,&BtForm::click,this,&Music::onBtFormClick);
    connect(ui->audio,&BtForm::click,this,&Music::onBtFormClick);
    connect(ui->like,&BtForm::click,this,&Music::onBtFormClick);
    connect(ui->local,&BtForm::click,this,&Music::onBtFormClick);
    connect(ui->recent,&BtForm::click,this,&Music::onBtFormClick);

    // 关联CommonPage发射的updateLikeMusic信号
    connect(ui->likepage,&CommonPage::updateLikeMusic,this,&Music::onUpdateLikeMuisc);
    connect(ui->localpage,&CommonPage::updateLikeMusic,this,&Music::onUpdateLikeMuisc);
    connect(ui->recentpage,&CommonPage::updateLikeMusic,this,&Music::onUpdateLikeMuisc);

    // 关联播放所有的信号和槽函数
    connect(ui->likepage,&CommonPage::playAll,this,&Music::onPlayAll);
    connect(ui->localpage,&CommonPage::playAll,this,&Music::onPlayAll);
    connect(ui->recentpage,&CommonPage::playAll,this,&Music::onPlayAll);

    // 处理likePage、localPage、recentPage中ListItemBox双击
    connect(ui->likepage,&CommonPage::playMusicByIndex,this,&Music::playMusicByIndex);
    connect(ui->localpage,&CommonPage::playMusicByIndex,this,&Music::playMusicByIndex);
    connect(ui->recentpage,&CommonPage::playMusicByIndex,this,&Music::playMusicByIndex);
    //关联静音
    connect(volumeTool,&VolumeTool::setSilence,this,&Music::setMusicSilence);
    //关联音量
    connect(volumeTool,&VolumeTool::setMusicVolume,this,&Music::setPlayerVolume);
//    //关联歌曲时间    媒体持续时⻓更新，即：⾳乐切换，时⻓更新，界⾯上时间也要更新
//    connect(player,&QMediaPlayer::durationChanged,this,&Music::onDurationChanged);
//    // 播放位置发⽣改变，即已经播放时间更新
//    connect(player,&QMediaPlayer::positionChanged,this,&Music::onPositionChanged);
    //关联进度条
    connect(ui->processbar,&MusicSlider::setMusicPositionslider,this,&Music::onMusicSliderChanged);
//    //关联歌曲信息
//    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&Music::onMetaDataAvailableChangedChanged);
    connect(ui->lrcword,&QPushButton::clicked,this,[=]()
    {
        lrcPage->show();
        lrcAnimation->start();
    });
}

void Music::onBtFormClick(int id)
{
    // 1.获取当前⻚⾯所有btFrom按钮类型的对象
    QList<BtForm*> buttonList = this->findChildren<BtForm*>();

    // 2.遍历所有对象, 如果不是当前id的按钮,则把之前设置的背景颜⾊清除掉
    foreach(BtForm* btitem,buttonList)
    {
        if(btitem->id != id)
        {
            btitem->clearBg();
            btitem->clearlinebox();
        }
    }

    // 3.设置当前栈空间显⽰⻚⾯
    ui->stackedWidget->setCurrentIndex(id-1);

    isDrag = false;
}

void Music::onCurrentIndexChanged(int index)
{
    currentIndex = index;
    // ⾳乐的id都在commonPage中的musicListOfPage中存储着
    const QString& musicID = currentPage->getMusicIDByIndex(index);
    // 有了MusicId就可以再musicList中找到该⾳乐
    auto it = musicList.findMusicById(musicID);
    if(it != musicList.end())
    {
        // 将该⾳乐设置为历史播放记录
        it->setHistory(true);
    }
    ui->recentpage->reFresh(musicList);
}

void Music::setMusicSilence(bool isMuted)
{
    player->setMuted(isMuted);
}

void Music::setPlayerVolume(int Volume)
{
    player->setVolume(Volume);
}


// 设置随机图⽚【歌曲的图⽚】
QJsonArray Music::RandomPicture()
{
    // 推荐⽂本 + 推荐图⽚路径
    QVector<QString> vecImageName;
    vecImageName << "001.png" << "003.png" << "004.png" << "005.png" << "006.png" << "007.png"
                 << "008.png" << "009.png" << "010.png" << "011.png" << "012.png" << "013.png"
                 << "014.png" << "015.png" << "016.png" << "017.png" << "018.png" << "019.png"
                 << "020.png" << "021.png" << "022.png" << "023.png" << "024.png" << "025.png"
                 << "026.png" << "027.png" << "028.png" << "029.png" << "030.png" << "031.png"
                 << "032.png" << "033.png" << "034.png" << "035.png" << "036.png" << "037.png"
                 << "038.png" << "039.png" << "040.png";
    std::random_shuffle(vecImageName.begin(),vecImageName.end());
    // 001.png
    // path: ":/images/rec/"+vecImageName[i];
    // text: "推荐-001"
    QJsonArray objArray;
    for(int i = 0;i < vecImageName.size();++i)
    {
        QJsonObject obj;
        obj.insert("path",":/images/rec/" + vecImageName[i]);

        // arg(i, 3, 10, QCchar('0'))
        // i：要放⼊%1位置的数据
        // 3: 三位数
        // 10：表⽰⼗进制数
        // QChar('0')：数字不够三位，前⾯⽤字符'0'填充
        QString strText = QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",strText);

        objArray.append(obj);
    }

    return objArray;
}

void Music::initSqlite()
{
    // 1. 创建数据库连接
    sqlite = QSqlDatabase::addDatabase("QSQLITE");

    // 2. 设置数据库名称
    sqlite.setDatabaseName("QQMusic.db");

    // 3. 打开数据库
    if(!sqlite.open())
    {
        QMessageBox::critical(this,"打开QQMusicDB失败",sqlite.lastError().text());
        return;
    }
    qDebug()<<"SQLite连接成功，并创建 [QQMusic.db] 数据库!!!";
    // 4. 创建数据库表
    QString sql = ("CREATE TABLE IF NOT EXISTS musicInfo(\
                   id INTEGER PRIMARY KEY AUTOINCREMENT,\
                   musicId varchar(200) UNIQUE,\
                   musicName varchar(50),\
                   musicSinger varchar(50),\
                   albumName varchar(50),\
                   duration BIGINT,\
                   musicUrl varchar(256),\
                   isLike INTEGER,\
                   isHistory INTEGER)");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        QMessageBox::critical(this,"创建数据库失败",query.lastError().text());
        return;
    }
    qDebug()<<"创建 [musicInfo] 表成功!!!";
}

void Music::initMusicList()
{
    // 1. 从数据库读取歌曲信息
    musicList.readFromDB();
    for(auto music: musicList.musicList)
    {
        music.plainMsg();
    }

    // 2. 更新CommonPage⻚⾯
    // 设置CommonPage的信息
    ui->likepage->setMusicListType(PageType::LIKE_PAGE);
    ui->likepage->reFresh(musicList);

    ui->localpage->setMusicListType(PageType::LOCAL_PAGE);
    ui->localpage->reFresh(musicList);
    // 将localPage中的歌曲添加到媒体播放列表中
    ui->localpage->addMusicToPlayList(musicList,playList);

    ui->recentpage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentpage->reFresh(musicList);
}

void Music::quitMusic()
{
    // 更新数据库
    musicList.writeToDB();
    // 关闭数据库连接
    sqlite.close();
    // 关闭窗⼝
    close();
}

//更新喜欢界面音乐
void Music::onUpdateLikeMuisc(bool isLike, QString musicId)
{
    // 1. 找到该⾸歌曲，并更新对应Music对象信息
    auto it = musicList.findMusicById(musicId);
    if(it != musicList.end())
    {
        it->setIsLike(isLike);
    }

    // 2. 通知三个⻚⾯更新⾃⼰的数据
    ui->likepage->reFresh(musicList);
    ui->localpage->reFresh(musicList);
    ui->recentpage->reFresh(musicList);
}

void Music::mouseMoveEvent(QMouseEvent *event)
{
    // 根据⿏标移动更新窗⼝位置
    if(event->buttons() == Qt::LeftButton && isDrag)
    {
        this->move(event->globalPos() - dragPosition);
        return;
    }

    QWidget::mouseMoveEvent(event);
}

void Music::mousePressEvent(QMouseEvent *event)
{
    //计算点击鼠标的坐标和lefttop坐标的距离
    // 拦截⿏标左键单击事件
    if(event->button() == Qt::LeftButton)
    {
        isDrag = true;
        // 获取⿏标相对于屏幕左上⻆的全局坐标
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        return;
    }

    QWidget::mousePressEvent(event);
}

void Music::playAllOfCommonPage(CommonPage *commonPage, int index)
{
    currentPage = commonPage;
    // 播放page所在⻚⾯的⾳乐
    // 将播放列表先清空，否则⽆法播放当前CommonPage⻚⾯的歌曲
    // 另外：该⻚⾯⾳乐不⼀定就在播放列表中，因此需要先将该⻚⾯⾳乐添加到播放列表
    playList->clear();

    // 将当前⻚⾯歌曲添加到播放列表
    commonPage->addMusicToPlayList(musicList,playList);

    // 设置当前播放列表的索引
    playList->setCurrentIndex(index);

    // 播放
    player->play();
}


void Music::on_quit_clicked()
{
    // 点击关闭按钮时，程序不退出，隐藏掉
    // ⽤⼾可以从系统托盘位置选择显⽰或者关闭
    hide();
}

void Music::on_volume_clicked()
{
    // 先要调整窗⼝的显⽰位置，否则该窗⼝在主窗⼝的左上⻆
    // 1. 获取该按钮左上⻆的图标
    QPoint point = ui->volume->mapToGlobal(QPoint(0,0));

    // 2. 计算volume窗⼝的左上⻆位置
    // 让该窗⼝显⽰在⿏标点击的正上⽅
    // ⿏标位置：减去窗⼝宽度的⼀半，以及⾼度恰巧就是窗⼝的左上⻆
    QPoint volumLeftTop = point - QPoint(volumeTool->width() / 2,volumeTool->height());

    //微调窗口位置
    volumLeftTop.setY(volumLeftTop.y() + 30);
    volumLeftTop.setX(volumLeftTop.x() + 15);

    // 3. 移动窗⼝位置
    volumeTool->move(volumLeftTop);

    // 4. 将窗⼝显⽰出来
    volumeTool->show();
}

//加载音乐按钮
void Music::on_addlocal_clicked()
{
    // 1. 创建⼀个⽂件对话框
    QFileDialog fileDialog(this);
    fileDialog.setWindowTitle("添加本地音乐");

    // 2. 创建⼀个打开格式的⽂件对话框
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);

    // 3. 设置对话框模式
    // 只能选择⽂件，并且⼀次性可以选择多个存在的⽂件
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    // 4. 设置对话框的MIME过滤器
    QStringList mimeList;
    mimeList << "application/octet-stream";
    fileDialog.setMimeTypeFilters(mimeList);

    // 5. 设置对话框默认的打开路径,设置⽬录为当前⼯程所在⽬录
    QDir dir(QDir::currentPath());
    dir.cdUp();
    QString musicPath = dir.path();
    musicPath += "/MusicPlayer/musics/";
//    qDebug() << musicPath << endl;
    fileDialog.setDirectory(musicPath);

    // 6. 显⽰对话框，并接收返回值
    // 模态对话框, exec内部是死循环处理
    if(fileDialog.exec() == QFileDialog::Accepted)
    {
        // 获取对话框的返回值
        QList<QUrl> urls = fileDialog.selectedUrls();

        // 拿到歌曲⽂件后，将歌曲⽂件交由musicList进⾏管理
        musicList.addMusicByUrl(urls);

        // 切换到本地⾳乐界⾯，因为加载完的⾳乐需要在本地⾳乐界⾯显⽰
        ui->stackedWidget->setCurrentIndex(4);

        //更新到本地⾳乐列表
        ui->localpage->reFresh(musicList);
    }
}

void Music::on_play_clicked()   // 播放按钮
{
    qDebug() << "播放按钮点击";
    if(player->state() == QMediaPlayer::PlayingState)
    {
        // 如果是歌曲正在播放中，按下播放键，此时应该暂停播放
        player->pause();
    }
    else if(player->state() == QMediaPlayer::PausedState)
    {
        // 如果是暂停状态，按下播放键，继续开始播放
        player->play();
    }
    else if(player->state() == QMediaPlayer::StoppedState)
    {
        player->play();
    }
}

void Music::onPlayStateChanged()
{
    qDebug() << "播放状态改变";
    if(player->state() == QMediaPlayer::PlayingState)
    {
        // 播放状态
        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }
    else
    {
        // 暂停状态
        ui->play->setIcon(QIcon(":/images/play3.png"));
    }
}

void Music::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{
    if(playbackMode == QMediaPlaylist::Loop)
    {
        ui->playmode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(playbackMode == QMediaPlaylist::Random)
    {
        ui->playmode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(playbackMode == QMediaPlaylist::CurrentItemInLoop)
    {
        ui->playmode->setIcon(QIcon(":/images/single_play.png"));
    }
    else
    {
        qDebug()<<"暂不⽀持该模式";
    }
}

void Music::on_playpre_clicked()
{
    playList->previous();
}

void Music::on_playnext_clicked()
{
    playList->next();
}

void Music::on_playmode_clicked()
{
    // 播放模式是针对播放列表的
    // 播放模式⽀持：循环播放、随机播放、单曲循环三种模式
    if(playList->playbackMode() == QMediaPlaylist::Loop)
    {
        // 列表循环
        ui->playmode->setToolTip("随机播放");
        playList->setPlaybackMode(QMediaPlaylist::Random);
    }
    else if(playList->playbackMode() == QMediaPlaylist::Random)
    {
        // 随机播放
        ui->playmode->setToolTip("单曲循环");
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else if(playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)
    {
        // 单曲循环
        ui->playmode->setToolTip("列表循环");
        playList->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
    {
        qDebug()<<"播放模式错误";
    }
}

void Music::onPlayAll(PageType pageType)
{
    CommonPage *page = nullptr;
    switch(pageType)
    {
        case PageType::LIKE_PAGE :
            page = ui->likepage;
            break;
        case PageType::LOCAL_PAGE :
            page = ui->localpage;
            break;
        case PageType::HISTORY_PAGE :
            page = ui->recentpage;
            break;
        default:
            qDebug() << "扩展";
    }

    // 从当前⻚⾯的零号位置开始播放
    playAllOfCommonPage(page,0);
}

void Music::playMusicByIndex(CommonPage *page, int index)
{
    playAllOfCommonPage(page,index);
}

void Music::onDurationChanged(qint64 duration)
{
    totalTime = duration;
    ui->tataltime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
}

void Music::onPositionChanged(qint64 position)
{
    // 1. 更新已经播放时间
    ui->currentTime->setText(QString("%1:%2").arg(position/1000/60,2,10,QChar('0')).arg(position/1000%60,2,10,QChar('0')));
    // 2. 进度条处理
    ui->processbar->setStep((float)position / (float)totalTime);
    // 3. 同步lrc歌词
    if(playList->currentIndex() >= 0)
    {
        lrcPage->showLrcWord(position);
    }
}

void Music::onMusicSliderChanged(float value)   //value是进度条的比例
{
    // 1. 计算当前seek位置的时⻓
    qint64 duration = (qint64)(value * totalTime);

    //2. 转换为百分制，设置当前时间
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));

    // 3. 设置当前播放位置
    player->setPosition(duration);
}

void Music::onMetaDataAvailableChangedChanged(bool available)
{
    (void)available;
    // 播放源改变
    qDebug() << "歌曲切换";

    QString musicId = currentPage->getMusicIDByIndex(currentIndex);
    auto it = musicList.findMusicById(musicId);
    QString musicName("未知歌曲");
    QString musicSinger("歌手位置");
    if(it != musicList.end())
    {
        musicName = it->getMusicName();
        musicSinger = it->getSingerName();
        qDebug() << "加载lrc歌词并解析" << endl;
        lrcPage->parseLrc(it->getLrcFilePath());
    }
    // 1. 从player播放歌曲的元数据中获取歌曲信息
//    QString singer = player->metaData("Author").toStringList().join(",");
//    QString musicName = player->metaData("Title").toString();
//    qDebug() << singer << musicName;
//    if(!musicName.isEmpty())
//    {
//        auto it = musicList.findMusicById(currentPage->getMusicIDByIndex(currentIndex));
//        if(it != musicList.end())
//        {
//            musicName = it->getMusicName();
//            singer = it->getSingerName();
//            qDebug() << "设置歌⼿、歌曲名称、专辑名称";
//        }
//    }

    // 2. 设置歌⼿、歌曲名称、专辑名称
    ui->musicname->setText(musicName);
    ui->musicsinger->setText(musicSinger);

    // 3. 获取封⾯图⽚
    QVariant coverImage = player->metaData("ThumbnailImage");
    if(coverImage.isValid())
    {
        // 获取封⾯图⽚成功
        QImage image = coverImage.value<QImage>();

        //设置封面图片
        ui->musiccover->setPixmap(QPixmap::fromImage(image));

        //缩放填充整个label
        ui->musiccover->setScaledContents(true);

        currentPage->setImageLable(QPixmap::fromImage(image));
    }
    else
    {
        // 设置默认图⽚-修改
        qDebug()<<"歌曲没有封面图";
                // 可以设置默认图片
        QString path = ":/images/rec/001.png";
        ui->musiccover->setPixmap(path);
        currentPage->setImageLable(path);
    }

    //歌词同步部分
    lrcPage->setTitle(musicName,musicSinger);
    // 此时需要知道媒体源在播放列表中的索引
//    QString musicId = currentPage->getMusicIDByIndex(currentIndex);
    qDebug() << musicId << endl;
//    auto it = musicList.findMusicById(musicId);

    // 加载lrc歌词并解析
//    if(it != musicList.end())
//    {
//        qDebug() << "加载lrc歌词并解析" << endl;
//        lrcPage->parseLrc(it->getLrcFilePath());
//    }
}


void Music::on_testSQL_clicked()
{
    // 加载数据库驱动
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    // 设置数据库名字
    db.setDatabaseName("QQMusic.db");
    //打开数据库
    if(!db.open())
    {
        qDebug()<<"QQMusic:"<<db.lastError().text();
    }
    qDebug() << "数据库QQMusic.db创建成功";
    // 关闭数据库连接，释放资源
//    db.close();
}

void Music::on_createtb_clicked()
{
    // 创建⼀个学⽣表，包含：学⽣id(主键，⾃动增⻓), 学⽣姓名(⾮空), 年龄，成绩绩点
    QString sql("CREATE TABLE IF NOT EXISTS student(\
                id INTEGER PRIMARY KEY AUTOINCREMENT,\
                name TEXT NOT NULL,\
                age INTEGER,\
                gpa REAL\
                )");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"学⽣表创建失败:"<<query.lastError().text();
        return;
    }
    qDebug() << "创建学⽣表成功!!!";
}

void Music::on_insert_clicked()
{
    QSqlQuery query;

    // 通过命名绑定
    query.prepare("INSERT INTO student(name, age, gpa) VALUES(:name, :age,:gpa)");
    query.bindValue(":name", "张三");
    query.bindValue(":age", 19);
    query.bindValue(":gpa", 3.5);
    if(!query.exec())
    {
        qDebug()<<"学⽣表插⼊数据:"<<query.lastError().text();
        return;
    }
    qDebug()<<"插⼊数据成功!!!";

    // 位置绑定
    query.prepare("INSERT INTO student(name, age, gpa) VALUES(?, ?, ?)");
    query.bindValue(0, "李四");
    query.bindValue(1,20);
    query.bindValue(2,4.0);
    if(!query.exec())
    {
        qDebug()<<"学⽣表插⼊数据:"<<query.lastError().text();
        return;
    }
    qDebug()<<"插⼊数据成功!!!";

    query.prepare("INSERT INTO student(name, age, gpa) VALUES(?, ?, ?)");
    query.addBindValue("王五");
    query.addBindValue(20);
    query.addBindValue(3.8);
    if(!query.exec())
    {
        qDebug()<<"学⽣表插⼊数据:"<<query.lastError().text();
        return;
    }
    qDebug()<<"插⼊数据成功!!!";

}


void Music::on_select_clicked()
{
    // 按照字段查询
    QString sql("SELECT name, age, gpa FROM student");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"查询学⽣表student失败："<<query.lastError().text();
        return;
    }
    // 按照字段名称获取查询到的结果
    while(query.next())
    {
        qDebug() << query.value("name").toString()
                 << query.value("age").toInt()
                 << query.value("gpa").toDouble() << endl;
    }
    qDebug()<<"===================================";
    // 查询所有列，按照索引获取
    sql = "SELECT * FROM student";
    if(!query.exec(sql))
    {
        qDebug()<<"查询学⽣表student失败："<<query.lastError().text();
        return;
    }

    // 按照字段名称获取查询到的结果
    while(query.next())
    {
        qDebug() << query.value(0).toInt()
                 << query.value(1).toString()
                 << query.value(2).toInt()
                 << query.value(3).toDouble() << endl;
    }
}

void Music::on_update_clicked()
{
    QSqlQuery query;
    query.prepare("UPDATE student SET age = :age WHERE name = :name");
    query.bindValue(":age",18);
    query.bindValue(":name", "王五");
    if(!query.exec())
    {
        qDebug()<<"更新学⽣信息失败："<<query.lastError().text();
        return;
    }
    qDebug()<<"查看更新结果：";


    QString sql = ("SELECT * FROM student WHERE name = '王五'");
    if(!query.exec(sql))
    {
        qDebug()<<"查询学⽣信息失败："<<query.lastError().text();
        return;
    }

    // 按照字段名称获取查询到的结果
    while(query.next())
    {
        qDebug() << query.value(0).toInt()
                 << query.value(1).toString()
                 << query.value(2).toInt()
                 << query.value(3).toDouble() << endl;
    }
}

void Music::on_del_clicked()
{
    QSqlQuery query;
    query.prepare("DELETE FROM student WHERE name = ?");
    query.addBindValue("王五");

    if(!query.exec())
    {
        qDebug()<<"删除学⽣信息失败："<<query.lastError().text();
        return;
    }

    qDebug()<<"查看删除结果：";
    QString sql("SELECT * FROM student");
    if(!query.exec(sql))
    {
        qDebug()<<"查询学⽣信息失败："<<query.lastError().text();
        return;
    }
    while(query.next())
    {
    qDebug()<<query.value(0).toInt()<<" "
            <<query.value(1).toString()<<" "
            <<query.value(2).toInt()<<" "
            <<query.value(3).toDouble();
    }
}

void Music::on_skin_clicked()
{
    QMessageBox::information(this,"温馨提⽰", "⼩哥哥正在加班紧急⽀持中...");
}

void Music::on_min_clicked()
{
    showMinimized();
}
